package com.aliang.shopping.util.ali;

import com.aliang.shopping.config.SMSConfig;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 短信工具类
 */

@Component
public class SMSTemplate {

    @Resource
    private SMSConfig smsConfig;


    public Integer getMaxCount() {
        return smsConfig.getMaxSendCount();
    }

    /**
     * 发送短信
     *
     * @param phoneNumber 手机号码
     * @param code        验证码
     * @return
     * @throws ClientException
     */
    public String send(String phoneNumber, String code) throws ClientException {
        DefaultProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(), smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", smsConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", smsConfig.getSign());//短信签名名称
        request.putQueryParameter("TemplateCode", smsConfig.getTemplateCode());//短信模板id
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//code填充的参数（JSON对象格式)

        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
        String json = response.getData();
        Gson g = new Gson();
        HashMap result = g.fromJson(json, HashMap.class);
        return result.get("Message").toString();
    }
}
